package com.cowin.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.cowin.base.annotation.LogAnnotation;
import com.cowin.base.auth.jwt.JwtUser;
import com.cowin.base.auth.jwt.JwtUtil;
import com.cowin.base.result.Result;
import com.cowin.base.result.ResultGenerator;
import com.cowin.base.BaseController;
import com.cowin.sys.model.TmSysUser;
import com.cowin.sys.service.TmSysUserService;
import com.cowin.utils.ValidateUserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by  on 2019/09/18.
 *
 * @author CodeGenerator
 */
@Api(value = "TmSysUserController", description = "系统用户控制器", tags = "TmSysUserController", consumes = "application/json")
@RestController
@RequestMapping("/tm/sys/user")
public class TmSysUserController {
    @Resource
    private TmSysUserService tmSysUserService;

    @Resource
    private JwtUtil jwtUtil;

    @LogAnnotation("Web系统登录")
    @ApiOperation(value = "Web系统登录", notes = "Web系统登录")
    @PostMapping("/login")
    public Result login(@RequestBody TmSysUser tmSysUser) {
        String password = tmSysUser.getPassword();
        String username = tmSysUser.getUsername();
        TmSysUser user = tmSysUserService.findUserByUserName(username);
        if (user != null) {
            boolean matches = ValidateUserUtils.matches(user, password);
            if (matches) {
                if ("1".equals(user.getUserStatus())) {
                    Map<String, Object> payloadMap = new HashMap<>(2);
                    payloadMap.put("userId", user.getTmSysUserId());
                    payloadMap.put("userName", user.getUsername());
                    String token = jwtUtil.generateToken(new JwtUser(user.getTmSysUserId(), user.getUsername(), user.getPassword(), null));
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("token", token);
                    jsonObject.put("payload", payloadMap);
                    return ResultGenerator.genSuccessResult(jsonObject);
                }
                return ResultGenerator.genFailResult("用户状态不可用");
            }
            return ResultGenerator.genFailResult("密码错误");
        }
        return ResultGenerator.genFailResult("用户名不正确");
    }
}
